package com.lighting.common.log;

import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.Callable;

public class MdcCallable<T> implements Callable<Object> {

    private Map<String, String> mdcContextMap;

    private Callable<Object> callable;

    public MdcCallable(Callable<Object> callable) {
        this.mdcContextMap = MDC.getCopyOfContextMap();
        this.callable = callable;
    }

    @Override
    public Object call() throws Exception {
        if (mdcContextMap != null && !mdcContextMap.isEmpty()) {
            MDC.setContextMap(mdcContextMap);
        }
        try {
            return callable.call();
        } finally {
            if (mdcContextMap != null && !mdcContextMap.isEmpty()) {
                MDC.clear();
            }
        }
    }
}